package com.sky.aop;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.ShoppingCartDTO;
import com.sky.properties.JwtProperties;
import com.sky.utils.GetHttp;
import com.sky.utils.JwtUtil;
import com.sky.utils.ParseJWTGetId;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class UserAddOrUpdate {

    private final JwtProperties jwtProperties;
    private final ParseJWTGetId parseJWTGetId;
    private final GetHttp getHttp;

    @Before("execution(* com.sky.service.user.*.*(..))")
    public void addCreateTime(JoinPoint joinPoint) {
        log.info("开始设置创建信息...");
        try {
            Object entity = getFirstEntity(joinPoint);
            if (entity == null) {
                log.warn("未找到实体参数，方法: {}", joinPoint.getSignature().getName());
                return;
            }

            // 使用RequestContextHolder获取HttpServletRequest
            HttpServletRequest request =getHttp.getCurrentHttpServletRequest();
            if (request == null) {
                log.warn("无法获取HttpServletRequest，方法: {}", joinPoint.getSignature().getName());
                return;
            }

            // 设置创建时间
            invokeSetterSafely(entity, "setCreateTime", LocalDateTime.now());

            // 从request中获取用户ID
            Integer userId =parseJWTGetId.getUserId(request);
            log.info("从token中获取到用户ID: {}", userId);
            invokeSetterSafely(entity, "setUserId", userId);

            log.info("设置创建信息完成: {}, userId: {}", entity.getClass().getSimpleName(), userId);
        } catch (Exception e) {
            log.error("设置创建信息失败: {}", e.getMessage(), e);
        }
    }



    /**
     * 获取第一个实体参数
     */
    private Object getFirstEntity(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            if (arg != null && !(arg instanceof ShoppingCartDTO)) {
                // 排除DTO类型，只处理实体类型
                if (!arg.getClass().getSimpleName().endsWith("DTO")) {
                    return arg;
                }
            }
        }
        return null;
    }

    /**
     * 安全调用setter方法
     */
    private void invokeSetterSafely(Object target, String methodName, Object value) {
        try {
            Method method = target.getClass().getMethod(methodName, value.getClass());
            method.invoke(target, value);
            log.debug("成功调用方法: {} with value: {}", methodName, value);
        } catch (NoSuchMethodException e) {
            log.trace("实体类 {} 没有方法 {}", target.getClass().getSimpleName(), methodName);
        } catch (Exception e) {
            log.warn("调用方法 {} 失败: {}", methodName, e.getMessage());
        }
    }
}
